package com.dflc.controller.SystemController;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dflc.common.CommonConstant;
import com.dflc.entity.po.*;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.req.RoleMenusReq;
import com.dflc.entity.req.RoleReq;
import com.dflc.mapper.SysRoleMapper;
import com.dflc.mapper.SysRoleMenuMapper;
import com.dflc.mapper.SysUserRoleMapper;
import com.dflc.service.SysMenuService;
import com.dflc.service.SysRoleMenuService;
import com.dflc.service.SysRoleService;
import com.dflc.service.TBackLoginUserService;
import com.dflc.utils.PageEntity;
import com.dflc.utils.PageEntityBuilder;
import com.dflc.utils.PageRequestEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色Controller控制器
 *
 * @author tqx
 * @site tqx
 * @company 数字涪陵
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private TBackLoginUserService tBackLoginUserService;


    /**
     * 获取全部角色
     *
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 获取全部角色
     */
    @PostMapping("/listAll")
    public HttpResponseEntity listAll(@RequestBody RoleReq req) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            List<SysRole> roleList = new ArrayList<>();
            TBackLoginUser tBackLoginUser = (TBackLoginUser) entity.getData();
                roleList = sysRoleService.list(new QueryWrapper<SysRole>().eq("state", CommonConstant.StateActive.Active)
                        .and(wrapper -> wrapper.eq("type", req.getType()))
                );
                return HttpResponseEntity.success(roleList);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 根据条件分页查询角色列表
     *
     * @param page
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 根据条件分页查询角色列表
     */
    @PostMapping("/list")
    public HttpResponseEntity list(@RequestBody PageRequestEntity page) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity2 = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity2.getStatus() != 200) {
                return entity2;
            }
            if (ObjectUtils.isEmpty(page.getQuery().get("type"))) {
                return HttpResponseEntity.error(500, "请选择角色终端类型！");
            }
            TBackLoginUser tBackLoginUser = (TBackLoginUser) entity2.getData();
            if (!org.springframework.util.ObjectUtils.isEmpty(tBackLoginUser) && tBackLoginUser.getIsAdmin().intValue() == CommonConstant.BackIsAdmin.Yes) {
                // 是超级管理员
                Page<SysRole> pageResult = sysRoleService.page(new Page<>(page.getCurrentPage(), page.getPageSize()),
                        new QueryWrapper<SysRole>().like(ObjectUtils.isNotEmpty(page.getQuery().get("name")),
                                        "name", page.getQuery().get("name"))
                                .eq("state", CommonConstant.StateActive.Active)
                                .eq(ObjectUtils.isNotEmpty(page.getQuery().get("type")), "type", page.getQuery().get("type"))
                );
                PageEntity entity = PageEntityBuilder.builder()
                        .data(pageResult.getRecords())
                        .currentPage(pageResult.getCurrent())
                        .pageSize(pageResult.getSize())
                        .totalCount(pageResult.getTotal())
                        .totalPage(pageResult.getPages())
                        .build();
                return HttpResponseEntity.success(entity);
            } else {
                //不是超级管理员 则不能查询
                return HttpResponseEntity.error(500, "您没有权限查询角色信息！");
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 添加或者修改
     *
     * @param sysRole
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 添加或者修改
     */
    @PostMapping("/save")
    public HttpResponseEntity save(@RequestBody @Valid SysRole sysRole) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            Map<String, Object> params3 = new HashMap<>();
            params3.put("name", sysRole.getName());
            params3.put("type", sysRole.getType());
            List<SysRole> list = sysRoleMapper.findAllByMap(params3);
            if (ObjectUtils.isEmpty(sysRole.getId())) {
                if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                    return HttpResponseEntity.error(500, "该角色名称已存在！");
                }
                sysRoleService.save(sysRole);
            } else {
                if (!ObjectUtils.isEmpty(list) && list.size() > 0 && list.get(0).getId().intValue() != sysRole.getId().intValue()) {
                    return HttpResponseEntity.error(500, "该角色名称已存在！");
                }
                sysRoleService.updateById(sysRole);
            }
            return HttpResponseEntity.success("操作成功！");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 删除-角色
     *
     * @param ids
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 删除
     */
    @Transactional
    @GetMapping("/delete/{ids}")
    public HttpResponseEntity delete(@PathVariable(value = "ids") String ids) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            List<String> strings = Arrays.stream(ids.split(",")).collect(Collectors.toList());
            List<Integer> integerList = new ArrayList<>();
            for (String string : strings) {
                integerList.add(Integer.parseInt(string));
            }

            //查询该角色和账号的关系是否有存在的绑定
            Map<String, Object> params2 = new HashMap<>();
            params2.put("roleIds", integerList);
            List<SysUserRole> list2 = sysUserRoleMapper.findAllWxByMap(params2);
            if (!org.springframework.util.ObjectUtils.isEmpty(list2) || list2.size() > 0) {
                return HttpResponseEntity.error(500, "选择的角色已绑定账号，无法删除！");
            }
            //查询该角色与权限的关系是否有存在的绑定
            Map<String, Object> params3 = new HashMap<>();
            params3.put("roleIds", integerList);
            List<SysRoleMenu> list3 = sysRoleMenuMapper.findAllByMap(params3);
            if (!org.springframework.util.ObjectUtils.isEmpty(list3) || list3.size() > 0) {
                return HttpResponseEntity.error(500, "选择的角色已绑定菜单，请先解除绑定！");
            }
            List<SysRole> sysRoles = sysRoleService.list(new QueryWrapper<SysRole>().in("id", integerList));
            for (SysRole sysRole : sysRoles) {
                sysRole.setState(CommonConstant.StateActive.Deleted);
            }
            sysRoleService.saveOrUpdateBatch(sysRoles);

            return HttpResponseEntity.success("删除成功！");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 获取当前角色的权限菜单
     *
     * @param id
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 获取当前角色的权限菜单
     */
    @GetMapping("/menus/{id}")
    public HttpResponseEntity menus(@PathVariable(value = "id") Integer id) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            List<Integer> integerList1 = new ArrayList<>();
            integerList1.add(id);
            List<SysMenu> list =  sysMenuService.getMenuByRoleIds(integerList1);
            return HttpResponseEntity.success(list);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 更新角色权限信息
     *
     * @param req
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 更新角色权限信息
     */
    @Transactional
    @PostMapping("/updateMenus")
    public HttpResponseEntity updateMenus(@RequestBody @Valid RoleMenusReq req) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            if (ObjectUtils.isEmpty(req.getId())) {
                return HttpResponseEntity.error(500, "角色id不能为空！");
            }
            if (ObjectUtils.isEmpty(req.getMenuIds())) {
                sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", req.getId()));
                return HttpResponseEntity.success("更新成功！");
            } else {
                List<SysRoleMenu> sysRoleMenuList = new ArrayList<>();
                List<String> strings = Arrays.asList(req.getMenuIds().split(","));
                for (String string : strings) {
                    SysRoleMenu roleMenu = new SysRoleMenu();
                    roleMenu.setMenuId(Long.valueOf(string));
                    roleMenu.setRoleId(Long.valueOf(req.getId()));
                    roleMenu.setType(Long.valueOf(CommonConstant.RoleMenuType.All));
                    sysRoleMenuList.add(roleMenu);
                }
                if (!ObjectUtils.isEmpty(req.getMenuHalfIds())){
                    List<String> strings2 = Arrays.asList(req.getMenuHalfIds().split(","));
                    for (String string : strings2) {
                        SysRoleMenu roleMenu = new SysRoleMenu();
                        roleMenu.setMenuId(Long.valueOf(string));
                        roleMenu.setRoleId(Long.valueOf(req.getId()));
                        roleMenu.setType(Long.valueOf(CommonConstant.RoleMenuType.Half));
                        sysRoleMenuList.add(roleMenu);
                    }
                }
                sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", req.getId()));
                sysRoleMenuService.saveBatch(sysRoleMenuList);
                return HttpResponseEntity.success("更新成功！");
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

}
